package com.weipai.turnplate.util;

import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author: 赵项阳
 * @Date: 2019/6/6 19:04
 * @Version 1.0
 */
public class FileUploadUtil {

    private static String imagePath = PropUtils.getString("image.path");

    private static String imageServerBaseUrl = PropUtils.getString("image.server.baseUrl");

    public static String ImgSave( HttpServletRequest request,MultipartFile img) {
        try {
            String filename = img.getOriginalFilename();
            String name = filename.substring(filename.indexOf("."), filename.length());
            filename = nonceStr() + name;
            //物理路径
            String filePath = imagePath + filename;
            //返回网络路径
            String url = imageServerBaseUrl + filename;
            FileCopyUtils.copy(img.getBytes(), new File(filePath));
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return "存储失败";
        }
    }

   /* public String ImgSave(HttpServletRequest request, MultipartFile[] image) {
        StringBuffer sb = new StringBuffer();
        String a = "";
        if (image != null && image.length > 0) {
            for (int i = 0; i < image.length; i++) {
                MultipartFile img = image[i];
                a = ImgSave(request, img);
                if (image.length == 1)
                    sb.append(a);
                else
                    sb.append(a + ",");
            }
        }
        return new String(sb);
    }*/

    public static String nonceStr() {
        return UUID.randomUUID().toString().toUpperCase().replaceAll("-", "");
    }
}
